package com.voxel.sense.infomsg.module.trace.details;

import android.os.Handler;
import android.text.TextUtils;

import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.L;
import com.example.com.common.utils.ListUtil;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.voxel.sense.infomsg.base.RecyclerViewPresenter;
import com.voxel.sense.infomsg.data.bean.ClockInMarkerBean;
import com.voxel.sense.infomsg.utils.GPSUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.ClockInsDetailsEntity;
import cyy.example.com.facotry.net.helper.NetHelper;

/**
 * Created by ChenYiYao on 2018/10/19.
 * des :
 */
public class CheckinsDetailsPresenter extends RecyclerViewPresenter<CheckinsDetailsContract.View>
        implements CheckinsDetailsContract.Presenter, DataSource.Callback<BaseEntity<ClockInsDetailsEntity>> {

    private Handler mHandler;
    private String mStartTime;
    private String mEndTime;
    private String mUserId;

    public CheckinsDetailsPresenter(CheckinsDetailsContract.View view) {
        super(view);
    }

    @Override
    protected void loadData() {
        NetHelper.getUserTraceDet(this, mUserId, mStartTime, mEndTime, getPageDataSize(), getPAGE_NUMB());
    }

    @Override
    protected void loadMoreData() {
        NetHelper.getUserTraceDet(this, mUserId, mStartTime, mEndTime, getPageDataSize(), getPAGE_NUMB());
    }

    @Override
    public void doLoadMore() {
        startLoadMoreData();
    }

    @Override
    public void doRefresh(String id, String startTime, String endTime) {
        mUserId = id;
        if (TextUtils.isEmpty(startTime) && TextUtils.isEmpty(endTime)) {
            //若为空，默认加载当月的数据
            Date start = new Date(System.currentTimeMillis());
            Date lastDayOfMonth = TimeUtils.getStartOfDay(TimeUtils.getLastDayOfMonth(start));
            Date firstDayDateOfMonth = TimeUtils.getEndOfDay(TimeUtils.getFirstDayDateOfMonth(start));
            L.d("---------time" + TimeUtils.date2String(lastDayOfMonth));
            L.d("---------time" + TimeUtils.date2String(firstDayDateOfMonth));
            mStartTime = "";
            mEndTime = "";
            startRefreshData();
            return;
        }
        //转成时间戳
        long milStart = TimeUtils.string2Millis(startTime, new SimpleDateFormat(Constants.TimeYMDFormat, Locale.getDefault()));
        //结束时间是改日的最大时刻
        Date endOFDay = TimeUtils.getEndOfDay(TimeUtils.string2Date(endTime, new SimpleDateFormat(Constants.TimeYMDFormat, Locale.getDefault())));
        long milEnd = TimeUtils.date2Millis(endOFDay);
        if (TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
            ToastUtil.showToastLong(Factory.app(), "请选择开始时间");
            mView.onRefreshFinish();
        } else if (!TextUtils.isEmpty(startTime) && TextUtils.isEmpty(endTime)) {
            ToastUtil.showToastLong(Factory.app(), "请选择结束时间");
            mView.onRefreshFinish();
        } else if (milStart > milEnd) {
            ToastUtil.showToastLong(Factory.app(), "开始时间不能大于结束时间");
            mView.onRefreshFinish();
        } else {
            //将时间转为服务器接收的格式
            mStartTime = milStart + "";
            //由于选择的时间都是整点的，结束时间应该是下一个整点之前的59分59秒
            mEndTime = milEnd + "";
            startRefreshData();
        }
    }

    @Override
    public void doHandlerItemEvent(Object data, String id, String des) {
        if (data != null && data instanceof ClockInsDetailsEntity.CoordinateListBean) {
            //转换实体
            ClockInsDetailsEntity.CoordinateListBean bean = (ClockInsDetailsEntity.CoordinateListBean) data;
            List<ClockInsDetailsEntity.CoordinateListBean.ValuesBean> values = bean.getValues();
            if (!ListUtil.isEmpty(values)) {
                List<ClockInMarkerBean> listData = new ArrayList<>();
                for (ClockInsDetailsEntity.CoordinateListBean.ValuesBean valuesBean : values) {
                    String latitude = valuesBean.getLatitude();
                    String longitude = valuesBean.getLongitude();
                    try {
                        double v = Double.parseDouble(latitude);
                        double v1 = Double.parseDouble(longitude);
                        //服务器获取到的坐标为百度坐标
                        double[] doubles = GPSUtils.bd09_To_Gcj02(v, v1);
                        ClockInMarkerBean clockInMarkerBean = new ClockInMarkerBean(valuesBean.getTime(), id, des, doubles[0], doubles[1]);
                        listData.add(clockInMarkerBean);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
                if (listData.size() > 0 && mView != null) {
                    mView.onSkipMap(listData);
                }
            }
        }
    }

    @Override
    public void onDataLoaded(BaseEntity<ClockInsDetailsEntity> data, int reqId) {
        List list = new ArrayList();
        if (data.isSuccess() && data.getData() != null && !ListUtil.isEmpty(data.getData().getCoordinateList())) {
            ClockInsDetailsEntity entity = data.getData();
            if (refreshIng) {
                String[] str = {"打卡总次数", entity.getSumCount()};
                String[] str1 = {"查询的时间段内打卡次数", entity.getTimeCount()};
                list.add(str);
                list.add(str1);
            }
            for (ClockInsDetailsEntity.CoordinateListBean bean : data.getData().getCoordinateList()) {
                List<ClockInsDetailsEntity.CoordinateListBean.ValuesBean> values = bean.getValues();
                if (values != null && values.size() > 0) {
                    list.add(bean);
                    list.addAll(values);
                }
            }
        }
        loadDataComplete(list);
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        loadDataComplete(null);
    }

}
